package DataCenter;

import java.io.*;
import java.util.Map;

import DataBasic.MetaConfig;
import DataBasic.Modifer;

public class ConfigModifier extends MetaConfig implements Modifer{

	private static ConfigModifier instance;
	
	public static synchronized ConfigModifier sharedInstance() {
		if (instance == null)
			instance = new ConfigModifier();
		return instance;
	}

	private InputStream inputStream;

	private ConfigModifier() {
		super();
	}

	/*
	 * modify system configuration
	 */
	
	@Override
	public void beginUpdate() {
		// modify the file in classpath (memory)
		try {
			inputStream = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME);
			this.prop.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void endUpdate() {
		try {
			FileOutputStream outStream = new FileOutputStream(FILE_PATH);
			prop.store(outStream, " ");
			outStream.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void updateSelfInfo(String name, String port, String state) {
		beginUpdate();
		Map<String, String> selfInfo = ConfigAccessor.sharedInstance().getSelfInfo();
		prop.setProperty("Name", name);
		selfInfo.put("Name", name);
		ConfigAccessor.sharedInstance().setName(name);
		prop.setProperty("Port", port);
		selfInfo.put("Port", port);
		prop.setProperty("State", state);
		selfInfo.put("State", state);
		endUpdate();
	}
	
	public void updateSelfState(String state) {
		beginUpdate();
		Map<String, String> selfInfo = ConfigAccessor.sharedInstance().getSelfInfo();
		prop.setProperty("State", state);
		selfInfo.put("State", state);
		endUpdate();
	}
	
}
